/*
 * @Author: 武志勇
 * @Date: 2022-12-23 11:18:37

 * @LastEditTime: 2024-05-17 16:07:20
 * @FilePath: \web-pc-svn\src\api\modules\index.js
 */
import axios from 'axios'
import type {AxiosResponse, AxiosRequestConfig} from "axios";
import UtilVar from "@/config/UtilVar";
import {GET_TOKEN} from "@/utils";

let baseUrl = UtilVar.baseUrl;
export {baseUrl}
axios.interceptors.request.use(
    function (config: AxiosRequestConfig): any {
        //在发送请求之前做什么 传token
        config.headers["Authorization"] = "Bearer " + GET_TOKEN();
        config.headers["Token"] = GET_TOKEN();
        //@ts-ignore
        config.headers["Content-Type"] = "application/json;charset=utf-8"
        return config;
    },
    function (error: any) {
        //对请求错误做什么操作
        console.log(error, '请求错误')
        return Promise.reject(error)
    }
)

export type Params = { [key: string]: string | number };
export type FileConfig = {
    setCancel?: Function;
    onProgress?: Function;
    [key: string]: any
}
/**
 * @响应拦截
 * */
axios.interceptors.response.use(
    (response: AxiosResponse) => {
        console.log(response,'response')
        if (response.status !== 200) {
            if(response.status === 401){
                uni.showToast({
                    title: '登录过期，请重新登录！',
                    icon: 'none',
                    duration: 1000
                })
            }
            return Promise.reject(response)
        }
        /**
         * @code 登录过期 token验证失败 根据后端调
         * */
        if (response.data.code == UtilVar.code) {
            return Promise.resolve(response)
        }
        return Promise.resolve(response)
    },
    (error: any) => {
        let err = {
            msg: "未知错误，请联系管理员！",
            success: false,
            code: 400
        }
        if (JSON.stringify(error).indexOf("Network Error") != -1) {
            err.msg = '网络错误或者服务器错误'
        }
        if (error.message == 'canceled') {
            err.msg = '取消请求'
            err.code = 488
        }
        if(error.response.status == 401){
            uni.showToast({
                title: '登录过期，请重新登录！',
                icon: 'none',
                duration: 1000
            })
            // router.push({ path: '/login', query: { timestamp: new Date().getTime() } });
            uni.navigateTo({
                url: '/pages/login/login',
                query: { timestamp: new Date().getTime() }
            })
        }else{
            uni.showToast({
                title: err.msg,
                icon: 'none',
                duration: 1000
            })
        }
        return Promise.reject(err)
    }
)

//判断是否是加密参数 是的话处理
let isEncryptionParam = (params: Params) => {
    return params
}
/**
 * @description:get 请求方法
 * @param {string} url 请求地址
 * @param {object} params 请求参数
 * @return {*}
 * */
export const GET = async (url: string, params: Params = {}): Promise<any> => {
    try {
        params = isEncryptionParam(params)
        const data = await axios.get(`${baseUrl}${url}`, {
            params: params,
        })
        return data.data
    } catch (error: any) {
        return Promise.reject(error.msg)
    }
}
/**
 * @description: post请求方法
 * @param {any} url
 * @param {any} params
 * @return {any}
 * */
export const POST = async (url: string, params: Params): Promise<any> => {
    try {
        params = isEncryptionParam(params)
        const data = await axios.post(`${baseUrl}${url}`, params)
        return data.data
    } catch (error: any) {
        return Promise.reject(error)
    }
}
